package org.infodavid.common.model.impl;

import java.io.Serializable;

import org.infodavid.common.model.IVersionObject;

/**
 * The Class AbstractVersionedObject.
 * @param <K> the key type
 */
public abstract class AbstractVersionedObject<K extends Serializable> extends
    AbstractImprovedDataObjectImpl<K> implements IVersionObject {

  /** serialVersionUID. */
  private static final long serialVersionUID = 6523279718688638433L;

  /** The reference. If null this version can have some data. */
  private Integer reference;

  /** The version. */
  private int revision;

  /**
   * constructor.
   * @param keyArg the key
   * @throws Exception the exception
   */
  protected AbstractVersionedObject(final K keyArg) throws Exception {
    this();

    setKey(keyArg);
  }

  /**
   * constructor.
   * @throws Exception the exception
   */
  protected AbstractVersionedObject() throws Exception {
    super();
  }

  /*
   * See super class or interface. (non-Javadoc)
   * @see org.infodavid.common.impl.model.DataObjectImpl#init()
   */
  @Override
  public void init() throws Exception {
    super.init();

    reference = null;
    revision = 0;
  }

  /*
   * See super class or interface. (non-Javadoc)
   * @see org.infodavid.common.model.IVersionObject#getRevision()
   */
  @Override
  public int getRevision() {
    return revision;
  }

  /*
   * See super class or interface. (non-Javadoc)
   * @see org.infodavid.common.model.IVersionObject#setRevision(java.lang.Integer)
   */
  @Override
  @SuppressWarnings("boxing")
  public void setRevision(final int value) {
    if (revision != value) {
      final Object old = revision;
      revision = value;
      markModified(REVISION, old, revision);
    }
  }

  /*
   * See super class or interface. (non-Javadoc)
   * @see org.infodavid.common.model.IVersionObject#getReference()
   */
  @Override
  public Integer getReference() {
    return reference;
  }

  /*
   * See super class or interface. (non-Javadoc)
   * @see org.infodavid.common.model.IVersionObject#setReference(java.lang.Integer)
   */
  @Override
  public void setReference(final Integer value) {
    if (!equals(reference, value)) {
        final Object old = reference;
        reference = value;
        markModified(REFERENCE, old, reference);
    }
  }

  /*
   * See super class or interface. (non-Javadoc)
   * @see org.infodavid.common.impl.model.DataObjectImpl#toString(java.lang.StringBuffer)
   */
  @Override
  protected StringBuffer toString(final StringBuffer builder) {
    super.toString(builder);

    builder.append("[ revision=");
    builder.append(revision);
    builder.append(", reference=");
    builder.append(reference);
    builder.append("]");

    return builder;
  }
}
